<template>
  <div class="container">
      <div class="title">编辑样式</div>
      <div class="content">
        <el-form ref="form" :model="formData" :rules="rules">
          <el-form-item label="门户名称" prop="name">
            <el-input v-model="formData.name" maxlength="20" show-word-limit :disabled="!isEdit"></el-input>
          </el-form-item>
          <el-form-item label="Banner设置" prop="bannerUrl">
              <el-upload
                drag
                :disabled="!isEdit"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :http-request="uploadRequest">
                  <div class="upload--text">
                    <img style="width: 300px; height:100px" v-if="formData.bannerUrl" :src="formData.bannerUrl" alt="">
                    <div v-else>
                      <img src="../../../../assets/img/uploadImg.png" alt="" style="height:29px;width:24px;margin-top:20px">
                      <div>
                        上传Banner图片
                      </div>
                    </div>
                  </div>
                </el-upload>
          </el-form-item>
          <el-form-item label="服务发起类型" prop="proposeTypeList">
              <div class="servertype-item" v-for="(server, index) in formData.proposeTypeList" :key="index">
                <span class="cancel-icon" @click="delSeverType(index)">
                  <icon-svg style="font-size: 8px;color: #fff;position:absolute;left:6px;top:3px" iconClass="guanbi"></icon-svg>
                </span>
                <el-select
                  style="width: 150px;margin-right: 10px;line-height:1"
                  v-model="server.modelId"
                  placeholder="请选择工单类型"
                  :disabled="!isEdit"
                  clearable
                  @change="handleServeTypeChange($event, index)"
                  @clear="handleServerTypeClear(index)"
                >
                  <el-option
                    v-for="item in billList"
                    :key="item.id"
                    :label="item.modelName"
                    :value="item.id"
                    value-key="id"
                    :disabled="getServerTypeItemDisabled(item.id)"
                  >
                  </el-option>
                </el-select>
                  <Aselect
                    class="aselect"
                    style="width: 103px"
                    ref="field"
                    v-model="server.icon"
                    :isSearch="false"
                    :options="iconList"
                    :disabled="!isEdit"
                    :inputWidth="100"
                    isIcon
                  >
                  ></Aselect>
              </div>
              <div class="service-type" @click="addSeverType">
                <icon-svg style="font-size: 10px" iconClass="xinzeng"></icon-svg>
                添加服务类型
              </div>
          </el-form-item>
        </el-form>
        <div class="item-label">客服热线</div>
        <el-input v-model="formData.hotLine" maxlength="20" show-word-limit :disabled="!isEdit"></el-input>
      </div>
      <div class="title">URL配置</div>
      <div class="content">
        <div class="item-label">用户移动端URL</div>
        <el-input v-model="formData.userUrl" disabled>
          <i slot="suffix" class="V7_iconfont V7_iconV7tubiao_fuzhi" @click="copyText(formData.userUrl)"></i>
        </el-input>
      </div>
      <div class="title">
        登录方式配置
        <el-tooltip popper-class="tooltip-class"  placement="bottom">
          <div slot="content">此项用于配置不同类型的用户所对应的登录方式；<br/>纯个人用户对应「个人用户登录」，手机号和验证码校验的方式登录；<br/>用户为企业时，对应「企业用户登录」，用分配的账号密码登录；<br/>若二者皆有，则采用「混合登录」。</div>
          <i class="V7_iconfont V7_iconV7tubiao_bangzhu-42" style="color:#B3B9C7; font-size:12px"></i>
        </el-tooltip>
      </div>
      <div class="content">
        <el-radio-group v-model="formData.loginType" :disabled="!isEdit">
          <el-radio :label="1">个人用户</el-radio>
          <el-radio :label="2">企业用户</el-radio>
          <el-radio :label="3">混合登录</el-radio>
        </el-radio-group>
        <div v-if="formData.loginType !== 2">
          <el-switch
            style="float: right"
            v-model="formData.allowWxBind"
            active-color="#2ED47A"
            inactive-color="#ff4949"
            :disabled="!isEdit"
          >
          </el-switch>
          <div class="bindphone-desc">允许微信授权绑定手机号</div>
        </div>
        <div v-if="formData.loginType !== 2" class="authorize-desc">绑定公众号后，若开启此项，个人用户可以获取授权，将微信号与手机号綁定（且无法解除绑定），再次通过鄉定微信号访问页面时，无需输入手机号和验证码即可登录。</div>
      </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { commonAction } from '@/utils/common'
import { uploadQiniu } from '@/utils/upload'
import Aselect from '@/afterSales/components/select/index.vue'
import Clipboard from 'clipboard-js'

@Component({
  name: 'PropertySetting',
  components: {
    Aselect
  }
})
export default class PropertySetting extends Vue {
  [x: string]: any
  @Prop({ default: false }) private isEdit!: boolean
  private formData = {
    name: '',
    bannerUrl: '',
    proposeTypeList: [{ modelId: '', proposeName: '', icon: '' }],
    hotLine: '',
    userUrl: '',
    loginType: 1,
    allowWxBind: true
  }

  private originFormData = {}

  private fileName = ''
  private isUploadSuccess = false
  private billList = [{ id: '', modelName: '' }]
  private iconList = [
    {
      value: 'weixiu1',
      label: 'weixiu1'
    },
    {
      value: 'anzhuang1',
      label: 'anzhuang1'
    },
    {
      value: 'baoyang1',
      label: 'baoyang1'
    },
    {
      value: 'tuihuan1',
      label: 'tuihuan1'
    },
    {
      value: 'weixiu2',
      label: 'weixiu2'
    },
    {
      value: 'anzhuang2',
      label: 'anzhuang2'
    },
    {
      value: 'baoyang2',
      label: 'baoyang2'
    },
    {
      value: 'tuihuan2',
      label: 'tuihuan2'
    },
    {
      value: 'weixiu3',
      label: 'weixiu3'
    },
    {
      value: 'anzhuang3',
      label: 'anzhuang3'
    },
    {
      value: 'baoyang3',
      label: 'baoyang3'
    },
    {
      value: 'tuihuan3',
      label: 'tuihuan3'
    }
  ]

  private validateProposeType = (rule: any, value: any, callback: any) => {
    if (value.some((item: { modelId: string }) => item.modelId === '')) {
      // eslint-disable-next-line standard/no-callback-literal
      callback('服务类型不能为空')
    } else if (value.some((item: { icon: string }) => item.icon === '' || item.icon === null)) {
      // eslint-disable-next-line standard/no-callback-literal
      callback('图标不能为空')
    } else {
      callback()
    }
  }

  public rules = {
    name: [
      { required: true, message: '请输入门户名称', trigger: 'blur' }
    ],
    bannerUrl: [
      { required: true, message: '请上传Banner图片', trigger: 'blur' }
    ],
    proposeTypeList: [
      { validator: this.validateProposeType, required: true, trigger: 'blur' }
    ]
  }

  public addSeverType () {
    if (this.isEdit) {
      this.formData.proposeTypeList.push({ modelId: '', proposeName: '', icon: '' })
    }
  }

  public delSeverType (index: number) {
    if (this.isEdit && this.formData.proposeTypeList && this.formData.proposeTypeList.length > 1) {
      this.formData.proposeTypeList.splice(index, 1)
    }
  }

  public getServerTypeItemDisabled (val: string) {
    return this.formData.proposeTypeList.some(item => item.modelId === val)
  }

  public handleServeTypeChange (val: string, index: number) {
    const billIndex = this.billList.findIndex(item => item.id === val)
    if (this.billList[billIndex]) {
      this.formData.proposeTypeList[index].proposeName = this.billList[billIndex].modelName
    }
  }

  public handleServerTypeClear (index: number) {
    this.formData.proposeTypeList[index].proposeName = ''
  }

  private copyText (content: string) { // 复制
    Clipboard.copy(content).then(() => {
      this.$message.success('复制成功')
    }).catch(() => {
      this.$message.error('复制失败')
    })
  }

  private created () {
    commonAction({
      url: '/server-work/action/workOrderModel/getCategory',
      method: 'post',
      data: {}
    }).then(res => {
      if (res.success) {
        this.billList = res.data
        return this.billList
      }
    })
    commonAction({
      url: '/server-work/action/facade/list',
      method: 'post',
      data: {}
    }).then(res => {
      const userProps = res.data.userVOList
      if (userProps) {
        const userProp = userProps[0]
        userProp.proposeTypeList = userProp.proposeTypeList.filter(item => item.deleteStatus === 0)
        this.formData = Object.assign(userProp)
        // 特殊处理icon
        if (userProp.proposeTypeList) {
          this.formData.proposeTypeList.forEach(item => {
            item.icon = item.icon.replace('icon-shouhouyun_', '')
          })
        } else {
          this.formData.proposeTypeList = [{ modelId: '', proposeName: '', icon: '' }]
        }
        this.formData.allowWxBind = userProp.allowWxBind === 1
        this.originFormData = JSON.parse(JSON.stringify(this.formData))
      } else {
        this.$emit('is-add', true)
      }
      return this.formData
    })
  }

  @Watch('formData', { deep: true })
  public formDataChange () {
    this.$emit('formData-change', this.formData)
  }

  private uploadRequest (request: any) {
    uploadQiniu({ type: 'crm', fileName: this.fileName }, request)
  }

  public beforeUpload (file: { name: string; size: number }) {
    this.fileName = file.name.replace(/\s/g, '')
    const type = file.name.substring(file.name.lastIndexOf('.') + 1)
    if (!['jpg', 'jpeg', 'png'].includes(type)) {
      this.$message.error('只能上传JPG/JPEG/PNG格式')
      return false
    }
    if (file.size > 500 * 1024) {
      this.$message.error(`附件大于${500}Kb`)
      return false
    }
  }

  public handleSuccess (response, file, fileList) {
    this.isUploadSuccess = true
    this.formData.bannerUrl = response.domain + '/' + response.key
  }
}
</script>
<style lang="stylus" scoped>
  .container
    float right
    width 340px
    height: 100%
    overflow auto
    background #FFFFFF
    box-shadow -1px 0px 4px 0px #E0E6F0
    border-radius 0px 0px 10px 0px
    .content
      padding 0 20px
      /deep/.el-radio-group
        height 50px
        line-height 50px
    .item-label
      font-size 12px
      font-family PingFang SC
      font-weight 400
      color #303753
      line-height 44px
    .upload--text
      height 100px
      width 300px
      font-size 12px
      font-family PingFang SC
      font-weight 400
      color #B3B9C7
      line-height 25px
    /deep/.el-upload-dragger
      width 300px
      height 100px
    .title
      padding 0 20px
      height: 55px
      line-height 55px
      font-size 14px
      font-family PingFang SC
      font-weight 600
      color #303753
      border-bottom 1px solid #ECF0F3
    .service-type
      font-size 12px
      font-family PingFang SC
      font-weight 400
      color #008BEE
      cursor pointer
    .servertype-item
      position relative
      display flex
      width 300px
      height 50px
      background #F8FAFD
      border-radius 4px
      margin-bottom 5px
      padding 10px
      .aselect
        /deep/.el-input--medium
          .el-input__inner
            line-height 30px
        /deep/.el-input
          .icon
            margin-top -12px
      .cancel-icon
        position absolute
        right 0
        top 0
        width 17px
        height 17px
        background #FC6B5C
        border-radius 0 0 0 17px
        cursor pointer
    .bindphone-desc
      height 20px
      line-height 20px
      width 132px
      font-size 12px
      font-family PingFang SC
      font-weight 400
      color #303753
    .authorize-desc
      font-size 12px
      font-family PingFang SC
      font-weight 400
      color #767E91
      line-height 20px
      margin-top 10px
</style>
